package com.work.service.main.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.work.constant.ExceptionDescription;
import com.work.dto.main.TallyMachineSearchDTO;
import com.work.dto.main.TallyMachineSubmitDTO;
import com.work.entity.main.TallyMachine;
import com.work.mapper.main.TallyMachineMapper;
import com.work.service.main.ITallyMachineService;
import com.work.vo.main.TallyMachineKindVO;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.core.tool.utils.Func;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 理货机械接口实现
 *
 * @author ：dujianyu
 * @since ：Created in 2024/5/21 14:14
 */
@Service
public class TallyMachineServiceImpl extends BaseServiceImpl<TallyMachineMapper, TallyMachine> implements ITallyMachineService {
    @Override
    public List<TallyMachineKindVO> selectTallyMachineTree(TallyMachineSearchDTO dto) {
        return baseMapper.selectTallyMachineTree(dto);
    }

    @Override
    public Boolean submitTallyMachineBatch(Long tallyId, List<TallyMachineSubmitDTO> dto) {
        if (!removeTallyMachineByTallyId(tallyId)) {
            throw new RuntimeException(ExceptionDescription.DB_ERROR + "清除旧理货机械失败");
        }

        if (Func.isEmpty(dto)) {
            return true;
        }

        List<TallyMachine> entityList = new ArrayList<>();
        for (TallyMachineSubmitDTO data : dto) {
            TallyMachine entity = BeanUtil.copy(data, TallyMachine.class);
            entity.setTallyId(tallyId);
            entityList.add(entity);
        }
        return super.saveOrUpdateBatch(entityList);
    }

    @Override
    public Boolean removeTallyMachineByTallyId(Long tallyId) {
        QueryWrapper<TallyMachine> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .select(TallyMachine::getId)
                .eq(TallyMachine::getIsDeleted, 0)
                .eq(TallyMachine::getTallyId, tallyId);
        List<TallyMachine> list = baseMapper.selectList(queryWrapper);
        if (Func.isNull(list) || Func.isEmpty(list)) {
            return true;
        }
        List<Long> ids = list.stream().map(TallyMachine::getId).collect(Collectors.toList());
        return super.deleteLogic(ids);
    }
}
